package com.dongdongshop.controller;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.data.Result;
import com.dongdongshop.data.ResultEnum;
import com.dongdongshop.pojo.SpecTwo;
import com.dongdongshop.pojo.TbSpecification;
import com.dongdongshop.pojo.TbTypeTemplate;
import com.dongdongshop.service.SpecificationService;
import com.dongdongshop.service.TemplateService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("typeController")
public class TypeController {

    @DubboReference
    private TemplateService templateService;

    @DubboReference
    private SpecificationService specificationService;

    @RequestMapping("getOneType")
    @ResponseBody
    public Result getOneType(Long typeId) {
        try {
            TbTypeTemplate tt = templateService.getOneType(typeId);
            return Result.respones(ResultEnum.SUCCESS).setData(tt);
        }catch (Exception e) {
            return Result.respones(ResultEnum.ERROR);
        }
    }

    @RequestMapping("getSpecInfo")
    @ResponseBody
    public Result getSpecInfo(Long typeId) {
        try {
            TbTypeTemplate tt = templateService.getOneType(typeId);
            List<TbSpecification> specifications = JSONObject.parseArray(tt.getSpecIds(),TbSpecification.class);
            List<SpecTwo> twoList = specifications
                    .stream()
                    .map(s -> {SpecTwo specTwo = specificationService.getOneSpecInfo(s.getId());return specTwo;})
                    .collect(Collectors.toList());
            return Result.respones(ResultEnum.SUCCESS).setData(twoList);
        }catch (Exception e) {
            return Result.respones(ResultEnum.ERROR);
        }
    }
}
